package alogrithm;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 12:50
 */
public class SortInList {
    public ListNode sortInList(ListNode head) {
        // write code here
        if (head == null || head.next == null) {
            return head;
        }
        // 使用快慢指针寻找中点
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        // 将链表切割
        ListNode newList = slow.next;
        slow.next = null;

        // 递归
        ListNode left = sortInList(head);
        ListNode right = sortInList(newList);

        ListNode dummyNode = new ListNode(0);
        ListNode cur = dummyNode;
        while (left != null && right != null) {
            if (left.val < right.val) {
                cur.next = left;
                left = left.next;
            } else {
                cur.next = right;
                right = right.next;
            }
            cur = cur.next;
        }
        cur.next = left != null ? left : right;
        return dummyNode.next;
    }

    public class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
}
